package com.ubxtech.cloud.config;

import com.ubxtech.cloud.interceptor.FeignAddHeaderRequestInterceptor;
import com.ubxtech.cloud.properties.CloudProperties;
import feign.Feign;
import feign.Logger;
import feign.RequestInterceptor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import jakarta.annotation.Resource;

/**
 * @author Victor.Xiao
 * @since 2022-01-18 15:16
 **/
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureAfter(EnableFeignClients.class)
public class OpenFeignAutoConfiguration {

    @Resource
    private Environment environment;

    @Bean
    @ConditionalOnMissingBean
    public RequestInterceptor requestInterceptor(CloudProperties cloudProperties) {
        return new FeignAddHeaderRequestInterceptor(environment.getProperty("spring.application.name",""),environment.getProperty("spring.cloud.nacos.discovery.metadata.version",""),cloudProperties);
    }

    /**
     * 打印Feign日志信息 级别,可以看到远程调用用时
     * # 还可以直接配置 feign.client.config.default.logger-level=FULL
     * feign:
     *   client:
     *     config:
     *       default: # 这里用default就是全局配置，如果是写服务名称，则是针对某个微服务的配置
     *         loggerLevel: Basic # 日志级别Basic
     */
    @Bean
    public Logger.Level level(){
        String level = environment.getProperty("ubxtech.cloud.logLevel");

        if (Logger.Level.FULL.toString().equalsIgnoreCase(level)) {
            return Logger.Level.FULL;
        }
        else if (Logger.Level.BASIC.toString().equalsIgnoreCase(level)) {
            return Logger.Level.BASIC;
        }
        else if (Logger.Level.HEADERS.toString().equalsIgnoreCase(level)) {
            return Logger.Level.HEADERS;
        }
        else {
            return Logger.Level.BASIC;
        }
    }
}
